#! /usr/bin/env python
# -*- coding:utf-8 -*-
# vim:fileencoding=utf-8

from pyscript.core.config import Config
from pyscript.model import Database

class Model(object):

    def __init__(self):
        """
        初始化数据库连接, Database(**kargs)
        db = dict(host = 'localhost',
                  port = 3306,
                  user = 'root',
                  password = '',
                  charset = 'utf8',
                  database = '',
                  connection_time = 0)
        Database(rdb=db, wdb_db=db, db = db)
        """
        config = Config()
        rdb = config.option('rdb', None)
        wdb = config.option('wdb', None)
        db = config.option('db', None)
        dbConfig = dict()

        if db:
            dbConfig['db'] = db

        if rdb:
            dbConfig['rdb'] = rdb

        if wdb:
            dbConfig['wdb'] = wdb

        self.db = Database(**dbConfig)

    @property
    def rdb(self):
        return self.db.rdb


    @rdb.deleter
    def rdb(self):
        del self.db.rdb


    @property
    def wdb(self):
        return self.db.wdb


    @wdb.deleter
    def wdb(self):
        del  self.db.wdb


    def select(self, query, params=None, db = None, method='fetchone', **kwargs):
        retval = None

        if not db:
            db = self.rdb

        try:
            cursor = db.cursor()
            cursor.execute(query, params)
        except Exception as e:
            print "Exception occur, message %s" % str(e)
        else:
            if hasattr(cursor, method):
                retval = getattr(cursor, method)(**kwargs)
            else:
                retval = cursor.fetchall()
            cursor.close()

        return retval


    def fetchone(self, query, params = None, db = None):
        if db is None:
            db = self.rdb

        return self.select(query, params, db, method='fetchone')


    def fetchall(self, query, params = None, db = None):
        if db is None:
            db = self.rdb

        return self.select(query, params, db, method = 'fetchall')


    def fetchmany(self, query, params = None, db=None, size = 1):
        if db is None:
            db = self.rdb

        if size < 1:
            size = 1

        return self.select(query, params, db, method = 'fetchmany', size = size)

